/*
 * Copyright 2010 Gal Dolber.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.unnison.demo.client.dynamic;

import com.google.gwt.user.client.ui.HasHTML;
import com.google.inject.Inject;

import com.unnison.demo.client.dynamic.DynamicPresenter.DynamicBinder;
import com.unnison.demo.client.main.MainPresenter;
import com.unnison.framework.client.GuitPresenter;
import com.unnison.framework.client.binder.Attribute;
import com.unnison.framework.client.binder.GuitBinder;
import com.unnison.framework.client.binder.ViewField;
import com.unnison.framework.client.binder.ViewHandler;
import com.unnison.framework.client.binder.ViewInitializer;
import com.unnison.framework.client.binder.contributor.HasAttribute;
import com.unnison.framework.client.binder.contributor.RunAsync;
import com.unnison.framework.client.place.Place;
import com.unnison.framework.client.place.PlaceName;

import java.util.ArrayList;

@RunAsync
@PlaceName("dynamic")
public class DynamicPresenter extends GuitPresenter<DynamicBinder> implements Place<Void> {

    public interface DynamicBinder extends GuitBinder<DynamicPresenter> {
    }

    final ArrayList<String> list = new ArrayList<String>();

    private final MainPresenter hasContent;

    @ViewField
    DynamicConstants constants;

    @ViewField
    HasHTML table;

    @Inject
    public DynamicPresenter(MainPresenter hasContent) {
        this.hasContent = hasContent;
    }

    @Override
    public void go(Void data) {
        hasContent.setContent(getView(), 1);
    }

    private void render() {
        StringBuilder sb = new StringBuilder();
        sb.append("<table>");
        for (String item : list) {
            sb.append("<tr>");

            sb.append("<td>");
            sb.append(item);
            sb.append("</td>");

            sb.append("<td>");
            sb.append("<button item='" + item + "'>Delete</button>");
            sb.append("</td>");

            sb.append("</tr>");
        }
        sb.append("</table>");
        table.setHTML(sb.toString());
    }

    @ViewHandler
    @ViewInitializer
    void reset$click() {
        list.clear();

        // Generate random data
        for (int n = 0; n < 10; n++) {
            String item = constants.buttonText() + n;
            list.add(item);
        }

        render();
    }

    @ViewHandler
    @HasAttribute("item")
    void table$click(@Attribute String item) {
        list.remove(item);
        render();
    }
}
